<template>
  <div class="d_main">
    <!-- 操作区 S-->
    <div class="d_operationBox">
      <div class="d_btn">
        <el-button type="primary" size="small" icon="el-icon-plus" v-permission="'MenuCode5-10-2-1'" @click="isAddSuppliers = true,modelTitle = '新建'">新建</el-button>
      </div>
      <div class="d_search">
      <screec
          v-model="search.QueryDataBaseFiled"
          :headData.sync="tableHead"
          :disabled="searchLoading"
        ></screec>
        <el-input
          v-model="search.likeWords"
          placeholder="请输入关键字"
          size="small"
          @keyup.enter.native="getAllSuppliers"
        >
          <el-button
            slot="append"
            :loading="searchLoading"
            type="primary"
            icon="el-icon-search"
            :disabled="searchLoading"
            element-loading-spinner="el-icon-loading"
            @click="getAllSuppliers"
          >
            搜索
          </el-button>
        </el-input>
      </div>
    </div>
    <!-- 操作区 E-->
    <!-- 表格操作区 S-->
    <div class="d_tableOperation">
      <div class="d_condition">

      </div>
      <div class="d_set">
        <div @click="getAllSuppliers"><i class="d_icon el-icon-refresh-right" /></div>
        <div class="setting flex">
          <HeadSeting :list-data.sync="tableHead" :table-code="$config.supplierlist" @reset="getTableHead" />
        </div>
      </div>
    </div>
    <!-- 表格操作区 E-->
    <!--table板块-->
    <div ref="tableCon" class="tableCon">
      <el-table
        v-show="tableHead.length>0"
        id="emtable"
        ref="multipleTable"
        v-loading="tabLoading"
        :data="allSuppliers"
        :height="tableHeight || 'auto'"
        border
        :summary-method="getSummaries"
        show-summary
        fit
        style="width: 100%"
        @header-dragend="surverWidth"
      >
        <!-- 复选框       -->
        <!--        <el-table-column type="selection" width="40" fixed="left" />-->
        <template v-for="(fruit,index) in tableHead">
          <el-table-column
            v-if="fruit.visible"
            :key="index"
            :label="fruit.columnName"
            :min-width="fruit.columnWidth || 110"
            :prop="fruit.columnCode"
            show-overflow-tooltip
            :fixed="fruit.isFloat?'left':false"
          >
            <template slot-scope="scope">
              {{ scope.row[fruit.columnCode] }}
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" width="70px" fixed="right" align="center">
          <template slot-scope="scope">
            <div>
              <el-popover
                :ref="`popover-${scope.$index}`"
                placement="bottom-end"
                popper-class="tableOp"
                width="160"
                :popper-options="{ boundariesElement: 'opBox', removeOnDestroy: true }"
                trigger="click"
              >
                <div class="operation">
                  <ul>
                        <li
                          v-if="scope.row.isEnabled===1"
                          @click="optionsClick('enable',scope.row)"
                           v-permission="'MenuCode5-10-2-5'"
                        >禁用
                        </li>
                        <li
                          v-if="scope.row.isEnabled===0"
                          @click="optionsClick('enable',scope.row)"
                          v-permission="'MenuCode5-10-2-4'"
                        >启用
                        </li>
                      <li  v-permission="'MenuCode5-10-2-2'" @click="optionsClick('modify',scope.row)">修改</li>
                      <li  v-permission="'MenuCode5-10-2-3'" @click="optionsClick('delete',scope.row)">删除</li>
                  </ul>
                </div>
                <div slot="reference" class="opBox pointer"><span class="el-icon-more c_3F61F1" /></div>
              </el-popover>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 骨架屏     -->
      <div class="p16" v-if="tableHead.length==0">
        <el-skeleton :rows="6" animated />
      </div>
    </div>
    <!--    分页-->
    <div class="paginaCon">
      <pagination
        :total="suppTotale||0"
        :page.sync="search.pageIndex"
        :limit.sync="search.pageSize"
        @pagination="getAllSuppliers"
      />
    </div>
    <!-- 新建供应商   -->
    <el-dialog
      title="新建供应商"
      :visible.sync="isAddSuppliers"
      :close-on-click-modal="false"
      custom-class="comDialog"
      width="40%"
      @close="closeDialog"
    >
      <div class="dialogDody">
        <el-form ref="supplierForm" :model="supplierForm" :rules="rules" label-width="95px" class="dialogForm">
          <el-form-item label="供应商编号">
            <el-input v-model="supplierForm.supplierCode" placeholder="系统自动生成" size="mini" disabled />
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="supplierForm.supplierName" placeholder="供应商名称" size="mini" />
          </el-form-item>
          <el-form-item label="供应商类型" prop="supplierType">
            <el-select
                        filterable v-model="supplierForm.supplierType" filterable placeholder="请选择供应商类型" size="mini">
              <el-option
                v-for="item in supplierTypes"
                :key="item.dicValueID"
                :label="item.displayValue"
                :value="item.dicValueCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="结算方式" prop="settlementWay">
            <el-select
                        filterable v-model="supplierForm.settlementWay" filterable placeholder="请输入仓库名称" size="mini">
              <el-option
                v-for="item in wayDataLists"
                :key="item.dicValueID"
                :label="item.displayValue"
                :value="item.dicValueCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="supplierForm.contactPerson" placeholder="请输入联系人" size="mini" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactMobile">
            <el-input v-model="supplierForm.contactMobile" placeholder="请输入联系电话" size="mini" />
          </el-form-item>
          <el-form-item label="供应商电话">
            <el-input v-model="supplierForm.supplierTel" placeholder="请输入供应商电话" size="mini" />
          </el-form-item>
          <el-form-item label="供应商地址">
            <el-cascader
              v-model="supplierForm.site"
              size="mini"
              :options="address"
              :props="{label:'areaName',value:'areaCode'}"
              @change="areaChange"
            />
          </el-form-item>
          <el-form-item label="" class="mt5">
            <el-input v-model="supplierForm.supplierAddress" type="textarea" placeholder="请输入内容" size="mini" />
          </el-form-item>
          <el-form-item label="备注" class="mt12">
            <el-input v-model="supplierForm.supplierRemark" type="textarea" placeholder="请输入内容" size="mini" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isAddSuppliers=false">取 消</el-button>
        <el-button
          v-loading="addLoading"
          :disabled="addLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="addSave"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑供应商   -->
    <el-dialog
      :title="modelTitle+'供应商'"
      :visible.sync="isEditSuppliers"
      :close-on-click-modal="false"
      custom-class="comDialog"
      width="40%"
      @close="closeDialog"
    >
      <div class="dialogDody">
        <el-form ref="editSupplierForm" :model="supplierForm" :rules="rules" label-width="95px" class="dialogForm">
          <el-form-item label="供应商编号">
            <el-input v-model="supplierForm.supplierCode" placeholder="系统自动生成" size="mini" disabled />
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="supplierForm.supplierName" placeholder="供应商名称" size="mini" />
          </el-form-item>
          <el-form-item label="供应商类型" prop="supplierType">
            <el-select
                        filterable v-model="supplierForm.supplierType" filterable placeholder="请选择供应商类型" size="mini">
              <el-option
                v-for="item in supplierTypes"
                :key="item.dicValueID"
                :label="item.displayValue"
                :value="item.dicValueCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="结算方式" prop="settlementWay">
            <el-select
                        filterable v-model="supplierForm.settlementWay" filterable placeholder="请输入仓库名称" size="mini">
              <el-option
                v-for="item in wayDataLists"
                :key="item.dicValueID"
                :label="item.displayValue"
                :value="item.dicValueCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="supplierForm.contactPerson" placeholder="请输入联系人" size="mini" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactMobile">
            <el-input v-model="supplierForm.contactMobile" placeholder="请输入联系电话" size="mini" />
          </el-form-item>
          <el-form-item label="供应商电话">
            <el-input v-model="supplierForm.supplierTel" placeholder="请输入供应商电话" size="mini" />
          </el-form-item>
          <el-form-item label="供应商地址">
            <el-cascader
              v-model="supplierForm.site"
              size="mini"
              :options="address"
              :props="{label:'areaName',value:'areaCode'}"
              @change="areaChange"
            />
          </el-form-item>
          <el-form-item label="" class="mt5">
            <el-input v-model="supplierForm.supplierAddress" type="textarea" placeholder="请输入内容" size="mini" />
          </el-form-item>
          <el-form-item label="备注" class="mt12">
            <el-input v-model="supplierForm.supplierRemark" type="textarea" placeholder="请输入内容" size="mini" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isEditSuppliers=false">取 消</el-button>
        <el-button
          v-loading="addLoading"
          :disabled="addLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="editSave"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import HeadSeting from '@/components/HeadSeting'
import screec from "@/components/screen";
import { arraySort } from '@/utils'

export default {
  name: 'Supplier',
  components: { Pagination, HeadSeting,screec },
  data() {
    var checkTel = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字'))
        } else {
          if (/^1[3-9]\d{9}$/.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 300)
    }
    return {
      searchLoading: false, // 搜索加载效果
      isAddSuppliers: false, // 新建弹框是否开启
      tabLoading: false, // 表格数据加载
      addLoading: false, // 新建供应商加载效果
      modelTitle:'',
      isEditSuppliers: false, // 编辑弹框是否开启
      // 供应商搜索条件
      search: {
        QueryDataBaseFiled:'',
        pageIndex: 1,
        pageSize: 30,
        likeWords: '',
        supplierType: '',
        supplierNature: '',
        supplierState: -1
      },
      suppTotale: 0, // 供应商总条数
      allSuppliers: [], // 供应商表格数据
      tableHead: [],
      address: [], // 地区联动数据
      tableHeight: null, // 表格最大高度
      operations: [
        [{ text: '修改', key: 'modify' }],
        [{ text: '启用', key: 'enable' }],
        [{ text: '删除', key: 'delete' }]
      ], // 表格操作
      supplierForm: {
        supplierCode: '',
        supplierName: '',
        supplierType: '',
        settlementWay: '',
        contactPerson: '',
        contactMobile: '',
        supplierTel: '',
        supplierAddress: '',
        supplierRemark: '',
        site: '',
        province: '',
        city: '',
        country: ''
      },
      supplierTypes: [], // 供应商类型
      wayDataLists: [], // 结算方式
      isEnabled: null,
      rules: {
        supplierName: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' }
        ],
        supplierType: [
          { required: true, message: '请选择供应商类型', trigger: 'blur' }
        ],
        settlementWay: [
          { required: true, message: '请选择结算方式', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        contactMobile: [
          { validator: checkTel, required: true, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 查询全部供应商
    this.getAllSuppliers()
    // 供应商表格得表头
    this.getTableHead()
    // 供应商类型
    this.getSupplierType()
    // 地区联动数据
    this.getArea()
    // 结算方式
    this.getWayList()
  },
  mounted() {
    // 表格高度
    this.calHeight()
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.multipleTable.doLayout()
    })
  },
  methods: {
    // 保存新建供应商
    addSave() {
      const parmas = this.supplierForm
      this.$refs.supplierForm.validate((valid) => {
        if (valid) {
          this.addLoading = true
          this.$api.warehouse.AddSupplier(parmas).then(() => {
            this.addLoading = false
            this.isAddSuppliers = false
            // 查询全部供应商
            this.getAllSuppliers()
            this.$message({
              message: '新建成功',
              type: 'success'
            })
          }).catch(() => {
            this.addLoading = false
          })
        }
      })
    },
    // 保存编辑供应商
    editSave() {
      const parmas = this.supplierForm
      this.$refs.editSupplierForm.validate((valid) => {
        if (valid) {
          this.addLoading = true
          this.$api.warehouse.UpdateSupplier(parmas).then(() => {
            this.addLoading = false
            this.isEditSuppliers = false
            // 查询全部供应商
            this.getAllSuppliers()
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
          }).catch(() => {
            this.addLoading = false
          })
        }
      })
    },
    // 供应商详情
    getInfo(id) {
      const parmas = {
        queryBy: 1,
        queryValue: id.toString()
      }
      this.$api.warehouse.GetSingleSupplier(parmas).then(res => {
        this.supplierForm = res
        const arry = []
        arry.push(res.province)
        arry.push(res.city)
        arry.push(res.country)
        this.supplierForm.site = arry
      })
    },
    // 删除供应商
    deleteSupplier(id) {
      const parmas = {
        entityID: id
      }
      this.$confirm('确定删除该供应商, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.warehouse.DeleteSupplier(parmas).then(() => {
          this.getAllSuppliers()
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        })
      })
    },
    // 设置供应商状态
    setSupplierSate(id) {
      const parmas = {
        supplierID: id,
        isDisabled: this.isEnabled
      }
      this.$confirm('确定启用/禁用, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.warehouse.ExcuteSupplier(parmas).then(() => {
          this.getAllSuppliers()
          this.$message({
            message: '设置成功',
            type: 'success'
          })
        })
      })
    },
    // 表格操作方法
    optionsClick(key, data) {
      if (key === 'modify') {
        // 修改
        this.modelTitle = '修改'
        this.isEditSuppliers = true
        this.getInfo(data.supplierID)
      } else if (key === 'enable') {
        // 启用/禁用设置
        this.isEnabled = Boolean(data.isEnabled)
        this.setSupplierSate(data.supplierID)
      } else if (key === 'delete') {
        // 删除
        this.deleteSupplier(data.supplierID)
      }
    },
    // 供应商类型
    getSupplierType() {
      this.$api.common.GetSupplierTypeDataList().then(res => {
        this.supplierTypes = res
      })
    },
    // 结算方式
    getWayList() {
      this.$api.common.GetSettlementWayDataList().then(res => {
        this.wayDataLists = res
      })
    },
    // 合计方法
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column.property === 'goodsCount' || column.property === 'purchaseSumAmount' || column.property === 'paiedSumAmount' || column.property === 'waitPaySumAmount') {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index]++
          } else {
            sums[index] = ' '
          }
        }
      })

      return sums
    },
    // 地区联动数据
    getArea() {
      this.$api.common.GetTreeAreaDataList().then(res => {
        this.address = res
      })
    },
    // 选择地址
    areaChange(val) {
      this.supplierForm.province = val ? val[0] : ''
      this.supplierForm.city = val ? val[1] : ''
      this.supplierForm.country = val ? val[2] : ''
    },
    // 保存表头样式变化
    saveHead(newArray) {
      const parmas = newArray
      setTimeout(() => {
        this.$api.common.saveTableStyle(parmas).then(() => {
        })
      }, 300)
    },
    // 保存表头列宽度
    surverWidth(newWidth, oldWidth, column) {
      setTimeout(() => {
        const heads = [...this.tableHead]
        heads.forEach(item => {
          if (item.columnCode === column.property) {
            item.columnWidth = column.width
            return
          }
        })
        this.saveHead(heads)
      }, 100)
    },
    // 获取供应商表格表头
    getTableHead() {
      const parmas = {
        tableCode: this.$config.supplierlist
      }
      this.$api.common.getAllTableHead(parmas).then(res => {
        res.sort(arraySort('columnSort'))
        this.tableHead = res
      })
    },
    // 查血全部供应商
    getAllSuppliers() {
      const parmas = this.search
      this.$api.warehouse.GetMatchPageSuppliers(parmas).then(res => {
        this.allSuppliers = res.list
        this.allSuppliers.forEach((item)=>{
            for(let i in item){
              if(!item[i] && item[i] !== 0){
                item[i] = '--'
              }
            }
          })
        this.suppTotale = res.totalCount
      })
    },
    calHeight() {
      this.$nextTick(() => {
        const rect = this.$refs.tableCon.getBoundingClientRect()
        this.tableHeight = rect.height
      })
    },
    // 关闭弹框事件
    closeDialog() {
      // 关闭弹框的时候清空数据
      if (this.$refs.supplierForm) {
        this.$refs.supplierForm.resetFields()
      }
      if (this.$refs.editSupplierForm) {
        this.$refs.editSupplierForm.resetFields()
      }
      this.supplierForm = this.$options.data().supplierForm
      this.wareShowper = '' // 清空管理员展示字段内容
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
